import { getRandomInterval } from "@/utils/timer";
import { defineStore } from "pinia";
import { updateLiveOnline } from "../LiveNewApi";
import { LiveDataStore } from "./LiveDataStore";

export const useOnlineTimer = defineStore("onlineTimer", () => {
  let onlineTimer: NodeJS.Timeout | null = null;
  const startOnlineUpdater = (liveDataStore: LiveDataStore) => {
    let randomInterval;
    const scheduleNextUpdate = () => {
      if (onlineTimer) {
        updateLiveOnline({
          ...liveDataStore.roomParams,
          onlineDuration: randomInterval
        }).then(data => {
          liveDataStore.roomWatchData.onlineCount = data.onlineCount;
        });
      }
      randomInterval = getRandomInterval();
      onlineTimer = setTimeout(scheduleNextUpdate, randomInterval * 1000);
    };

    scheduleNextUpdate();
  };
  const resetOnlineUpdater = (liveDataStore: LiveDataStore) => {
    endOnlineUpdater();
    startOnlineUpdater(liveDataStore);
  };
  const endOnlineUpdater = () => {
    if (onlineTimer) {
      clearTimeout(onlineTimer);
      onlineTimer = null;
    }
  };
  return { startOnlineUpdater, endOnlineUpdater, resetOnlineUpdater };
});

export type OnlineTimerStore = ReturnType<typeof useOnlineTimer>;
